#!/usr/bin/env.python
# -*- coding: utf-8 -*-
import numpy as np
import os
import operator
# 文本数字识别系统·································································
def classify0(x, data_set, labels, k):
    # KNN分类器函数
    data_size = data_set.shape[0]
    diff_mat = np.tile(x, (data_size, 1)) - data_set
    sq_diff_mat = diff_mat**2
    sq_distances = sq_diff_mat.sum(axis=1)
    distances = sq_distances**0.5
    sort_distances = distances.argsort()
    class_count = {}
    for i in range(k):
        vote_label = labels[sort_distances[i]]
        class_count[vote_label] = class_count.get(vote_label, 0) + 1
    sort_class_distances = sorted(class_count.items(), key=operator.itemgetter(1), reverse=True)
    return sort_class_distances[0][0]

def img2vector(filename):
    '''将图像文本转换为测试向量。'''
    return_vector = np.zeros((1, 1024))
    fr = open(filename)
    for i in range(32):
        line_str = fr.readline()
        for j in range(32):
            return_vector[0, 32*i+j] = int(line_str[j])
    return return_vector

def hand_writing_class_test():
    hw_ables = []
    training_file_list = os.listdir("trainingDigits")      # 文件
    m = len(training_file_list)
    trainMat = np.zeros((m, 1024))
    for i in range(m):
        fileNameStr = training_file_list[i]
        file_str = fileNameStr.split(".")[0]
        class_num_str = int(file_str.split("_")[0])
        hw_ables.append(class_num_str)
        trainMat[i, :] = img2vector("trainingDigits\\%s" % fileNameStr)        # 文件
    testFile_list = os.listdir("testDigits")                 # 文件
    error_count = 0
    mTest = len(testFile_list)
    for j in range(mTest):
        file_test_str = testFile_list[j]
        file_test_num = file_test_str.split(".")[0]
        test_labels = int(file_test_num.split("_")[0])
        vector_under_test = img2vector("testDigits\\%s" % file_test_str)         # 文件
        class_fire_result = classify0(vector_under_test, trainMat, hw_ables, 5)
        print("the classfire come back with:%d, the real answer is:%d" % (class_fire_result, test_labels))
        if class_fire_result != test_labels:
            error_count += 1.0
    print("\n the total num is:%d" % error_count)
    print("\n the total num rate is:%f" % (error_count/float(mTest)))


